package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.commons.scheduled.TaskAction;
import cn.fetosoft.commons.scheduled.TaskInfo;
import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.entity.Scheduled;
import cn.fetosoft.woodpecker.core.data.form.ScheduledForm;
import cn.fetosoft.woodpecker.core.data.service.ElementService;
import cn.fetosoft.woodpecker.core.data.service.ScheduledService;
import cn.fetosoft.woodpecker.core.enums.ScheduledStatus;
import cn.fetosoft.woodpecker.core.exceptions.ValidatorException;
import cn.fetosoft.woodpecker.struct.DataGrid;
import cn.fetosoft.woodpecker.struct.UserIdentity;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/7/27 17:57
 */
@Slf4j
@Controller
@RequestMapping("/auth/scheduled")
public class ScheduledController extends BaseController {

	@Autowired
	private ScheduledService scheduledService;
	@Autowired
	private cn.fetosoft.commons.scheduled.ScheduledService taskService;
	@Autowired
	private ElementService elementService;

	@RequestMapping("/main")
	public String main(){
		return "/scheduled/main";
	}

	/**
	 * 查询定时任务
	 * @param form
	 * @return
	 */
	@RequestMapping("/getScheduleds")
	@ResponseBody
	public String getScheduleds(@ModelAttribute ScheduledForm form){
		DataGrid<Scheduled> dataGrid = new DataGrid<>();
		form.setAscField("createTime");
		try {
			long total = scheduledService.selectCountByForm(form, Scheduled.class);
			dataGrid.setTotal(total);
			if(total>0){
				List<Scheduled> list = scheduledService.selectListByForm(form);
				dataGrid.setRows(list);
			}
		}catch (Exception e){
			log.error("getScheduleds", e);
		}
		return dataGrid.toJsonString();
	}

	/**
	 * 创建
	 * @return
	 */
	@RequestMapping("/create")
	@ResponseBody
	public String create(@ModelAttribute Scheduled scheduled, HttpServletRequest request){
		Result<String> result = Result.errorResult();
		try{
			UserIdentity identity = this.getSessionUser(request);
			scheduled.setUserId(identity.getUserId());
			scheduled.setJobClass("cn.fetosoft.woodpecker.core.scheduled.TestPlanExecuteJob");
			scheduled.setStatus(ScheduledStatus.Stop.getValue());
			scheduled.setCreateTime(System.currentTimeMillis());
			scheduledService.insert(scheduled);
			result.setStatus(Result.SUCCESS);
		}catch (ValidatorException e){
			result.setErrorMsg(e.getMessage());
		}catch (Exception e){
			result.setErrorMsg(e.getMessage());
			log.error("create", e);
		}
		return result.toString();
	}

	/**
	 * 更新
	 * @param scheduled
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public String update(@ModelAttribute Scheduled scheduled){
		Result<String> result = Result.errorResult();
		try{
			if(StringUtils.isBlank(scheduled.getId())){
				result.setErrorMsg("ID不能为空！");
				return result.toString();
			}
			scheduled.setModifyTime(System.currentTimeMillis());
			UpdateResult r = scheduledService.update(scheduled);
			if(r.getModifiedCount()>0) {
				result.setStatus(Result.SUCCESS);
			}
		}catch (ValidatorException e){
			result.setErrorMsg(e.getMessage());
		}catch (Exception e){
			result.setErrorMsg(e.getMessage());
			log.error("create", e);
		}
		return result.toString();
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam String id){
		Result<String> result = Result.errorResult();
		DeleteResult r = scheduledService.deleteById(id, Scheduled.class);
		if(r.getDeletedCount()>0){
			result.setStatus(Result.SUCCESS);
		}else{
			result.setErrorMsg("删除失败！");
		}
		return result.toString();
	}

	/**
	 * 启动
	 * @param id
	 * @return
	 */
	@RequestMapping("/start")
	@ResponseBody
	public String start(String id){
		Result<String> result = Result.errorResult();
		try {
			Scheduled scheduled = scheduledService.findById(id, Scheduled.class);
			if(ScheduledStatus.Running.getValue()==scheduled.getStatus()){
				TaskInfo taskInfo = this.buildTaskInfo(scheduled, TaskAction.STOP);
				taskService.stop(taskInfo);
			}
			TaskInfo taskInfo = this.buildTaskInfo(scheduled, TaskAction.START);
			cn.fetosoft.commons.scheduled.Result taskResult = taskService.start(taskInfo);
			if (taskResult == cn.fetosoft.commons.scheduled.Result.SUCCESS) {
				result.setStatus(Result.SUCCESS);
				result.setErrorMsg("启动成功！");
			}else{
				result.setErrorMsg("启动失败！");
			}
		} catch (Exception e) {
			log.error("start",e);
		}
		return result.toString();
	}

	/**
	 * 停止
	 * @param id
	 * @return
	 */
	@RequestMapping("/stop")
	@ResponseBody
	public String stop(String id){
		Result<String> result = Result.errorResult();
		try {
			Scheduled scheduled = scheduledService.findById(id, Scheduled.class);
			TaskInfo taskInfo = this.buildTaskInfo(scheduled, TaskAction.STOP);
			cn.fetosoft.commons.scheduled.Result taskResult = taskService.stop(taskInfo);
			if (taskResult == cn.fetosoft.commons.scheduled.Result.SUCCESS) {
				result.setStatus(Result.SUCCESS);
				result.setErrorMsg("停止成功！");
			}else{
				result.setErrorMsg("停止失败！");
			}
		} catch (Exception e) {
			log.error("stop",e);
		}
		return result.toString();
	}

	private TaskInfo buildTaskInfo(Scheduled scheduled, TaskAction action){
		BaseElement element = (BaseElement) elementService.findById(scheduled.getPlanId(), BaseElement.class);
		TaskInfo taskInfo = new TaskInfo();
		taskInfo.setAction(action.getCode());
		taskInfo.setCode(scheduled.getId());
		taskInfo.setName(scheduled.getName());
		taskInfo.setDescription(scheduled.getDescription());
		taskInfo.setExpression(scheduled.getExpression());
		taskInfo.setJobClass(scheduled.getJobClass());
		JSONObject params = new JSONObject();
		params.put("planId", element.getPlanId());
		params.put("userId", scheduled.getUserId());
		taskInfo.addAllParams(params);
		return taskInfo;
	}
}
